#ifndef BINDER_H
#define BINDER_H

#include <sys/ioctl.h>
#include "uapi_binder.h"

struct binder_state;

struct binder_io {
    char *data;
    binder_size_t *offs;
    size_t data_avail;
    size_t offs_avail;

    char *data0;
    binder_size_t *offs0;
    uint32_t flags;
    uint32_t unused;
};

struct binder_death {
    void (*func)(struct binder_state *bs, void *ptr);

    void *ptr;
};

#define BINDER_SERVICE_MANAGER  0U

#define SVC_MGR_NAME "ServiceManager"

enum {
    PING_TRANSACTION = B_PACK_CHARS('_', 'P', 'N', 'G'),
    SVC_MGR_GET_SERVICE = 1,
    SVC_MGR_CHECK_SERVICE,
    SVC_MGR_ADD_SERVICE,
    SVC_MGR_LIST_SERVICES,
};

typedef int (*binder_handler)(struct binder_state *bs,
                              struct binder_transaction_data *txn,
                              struct binder_io *msg,
                              struct binder_io *reply);

struct binder_state *binder_open(size_t mapsize);

extern void binder_close(struct binder_state *bs);


extern int binder_call(struct binder_state *bs,
                       struct binder_io *msg, struct binder_io *reply,
                       uint32_t target, uint32_t code);

extern void binder_done(struct binder_state *bs,
                        struct binder_io *msg, struct binder_io *reply);

extern void binder_acquire(struct binder_state *bs, uint32_t target);

extern void binder_release(struct binder_state *bs, uint32_t target);

extern void binder_link_to_death(struct binder_state *bs, uint32_t target, struct binder_death *death);

extern void binder_loop(struct binder_state *bs, binder_handler func);

extern int binder_become_context_manager(struct binder_state *bs);

extern void bio_init(struct binder_io *bio, void *data,
                     size_t maxdata, size_t maxobjects);

extern void bio_put_obj(struct binder_io *bio, void *ptr);

extern void bio_put_ref(struct binder_io *bio, uint32_t handle);

extern void bio_put_uint32(struct binder_io *bio, uint32_t n);

extern void bio_put_string16(struct binder_io *bio, const uint16_t *str);

extern void bio_put_string16_x(struct binder_io *bio, const char *_str);

extern void bio_put_data(struct binder_io *bio, const uint16_t *data, size_t size);

extern void bio_put_data_x(struct binder_io *bio, const char *data, size_t size);

extern uint32_t bio_get_uint32(struct binder_io *bio);

extern uint16_t *bio_get_string16(struct binder_io *bio, size_t *sz);

extern uint16_t *bio_get_data(struct binder_io *bio, size_t *sz);

extern uint32_t bio_get_ref(struct binder_io *bio);

extern uint32_t svcmgr_lookup(struct binder_state *bs, uint32_t target, const char *name);

extern int svcmgr_publish(struct binder_state *bs, uint32_t target, const char *name, void *ptr);

#endif
